(function () {
  'use strict';

  angular
    .module('client')
    .factory('authInterceptor', authInterceptor);

  authInterceptor.$inject = ['$rootScope', '$q', 'API_PREFIX', 'AUTH_EVENTS', 'AuthService', 'HTTP_STATUS_CODES'];
  function authInterceptor($rootScope, $q, API_PREFIX, AUTH_EVENTS, AuthService, HTTP_STATUS_CODES) {
    //TODO: use http-buffer: retry request
    var interceptor = {
      request: request,
      response: response,
      responseError: responseError
    };

    return interceptor;

    function request(config) {

      var token = AuthService.getToken();
      if (0 === config.url.indexOf(API_PREFIX) && token) {
        config.headers.Authorization = 'Bearer ' + token;
      }

      return config;
    }

    function response(res) {
      if (0 === res.config.url.indexOf(API_PREFIX) && res.data.token) {
        AuthService.saveToken(res.data.token);
      }

      return res;
    }

    function responseError(rejection) {
      var config = rejection.config || {};
      if (!config.ignoreAuthModule) {
        switch (rejection.status) {
          case HTTP_STATUS_CODES.UNAUTHORIZED:
            var deferred = $q.defer();
            $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated, rejection);
            return deferred.promise;
          case HTTP_STATUS_CODES.FORBIDDEN:
            $rootScope.$broadcast(AUTH_EVENTS.notAuthorized, rejection);
            break;
        }
      }
      // otherwise, default behaviour
      return $q.reject(rejection);
    }
  }

})();
